package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.list.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @Author: zm
 * @Date: 2021/8/25 22:01
 */
@Component
public class GoodsReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 上架
     * @param skuId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void upperGoodsToEs(Long skuId, Message message, Channel channel) {
        try {
            if (skuId != null) {
                searchService.upperGoods(skuId);
            }
        } catch (Exception e) {
            // 记录日志...... 谁没有上架成功！ 记录表 table！
            e.printStackTrace();
        }
        // 手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    /**
     * 下架
     * @param skuId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void lowerGoodsToEs(Long skuId, Message message, Channel channel) {
        try {
            if (skuId != null) {
                searchService.lowerGoods(skuId);
            }
        } catch (Exception e) {
            // 记录日志...... 谁没有下架成功！ 记录表 table！
            e.printStackTrace();
        }
        // 手动确认  第二个参数 true表示批量处理,false 表示确认一个消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
